package cn.lbd.kill.server.service;

import cn.lbd.kill.model.dto.KillSuccessUserInfo;
import cn.lbd.kill.model.entity.ItemKillSuccess;
import cn.lbd.kill.model.mapper.ItemKillSuccessMapper;
import cn.lbd.kill.server.dto.MailDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

@Service
public class RabbitReceiveService {
    private static final Logger logger = LoggerFactory.getLogger(RabbitReceiveService.class);
    @Autowired
    private MailService mailService;
    @Autowired
    private Environment environment;
    @Autowired(required = false)
    private ItemKillSuccessMapper itemKillSuccessMapper;

    /**
     * 生产者只管推送消息到MQ，然后可以做其他任务，邮件的发送时机即消费者监听到MQ消息的时机，实现 异步 发送邮件
     */
    @RabbitListener(queues = {"${mq.kill.item.success.email.queue}"}, containerFactory = "singleListenerContainer")
    public void receiveKillSuccessEmailMsg(KillSuccessUserInfo info) {
        try {
            logger.info("秒杀异步邮件通知，接收信息：{}", info);
            System.out.println("秒杀异步邮件通知，接收信息：" + info);
            String contents = String.format(environment.getProperty("mail.kill.item.success.content"), info.getItemName(), info.getCode());
            MailDTO mailDTO = new MailDTO(environment.getProperty("mail.kill.item.success.subject"), new String[]{info.getEmail()}, contents);
            //异步的发送邮件
            mailService.sendEmail(mailDTO);
        } catch (Exception e) {
            logger.error("秒杀异步邮件通知，接收信息-发生异常：{}", e.fillInStackTrace());
        }
    }


    /**
     * 用户秒杀成功后超时未支付-监听者
     * 利用死信队列进行超时未支付订单的失效
     *
     * @param info
     */
    @RabbitListener(queues = {"${mq.kill.item.success.kill.dead.real.queue}"}, containerFactory = "multiListenerContainer")
    public void receiveExpireKillSuccessMsg(KillSuccessUserInfo info) {
        try {
            logger.info("用户秒杀成功后超时未支付-监听者-接收消息:{}", info);
            if (info != null) {
                ItemKillSuccess itemKillSuccess = itemKillSuccessMapper.selectByPrimaryKey(info.getCode());
                if (itemKillSuccess != null && itemKillSuccess.getStatus().intValue() == 0) {
                    //当状态是成功未付款时，将订单状态改为失效。当状态变为已付款或取消时，不作处理
                    itemKillSuccessMapper.expireOrder(info.getCode());
                }
            }
        } catch (Exception e) {
            logger.error("用户秒杀成功后超时未支付-监听者-发生异常：", e.fillInStackTrace());
        }
    }

}
